var ZYRequestClient = require("../../../../utils/zy-request");
var requestClient;
const app = getApp();
Page({
  data:{
    companyId:0,
    parentId:0,
    level:0,
    departmentName:"",
    showDepartmentAction:false,
    showUserAction:false,
    showAddDialog:false,
    showUpdateDialog:false,
    showCheckDialog:false,
    checkDepartmentId:0,
    selectedDepartment:null,
    selectedUser:null,
    departmentList:[],
    userList:[],
    departmentActionButtons:[{text:'编辑部门',value:'edit'},{text:'解散部门',type: 'warn',value:'remove'}],
    userActionButtons:[{text:'归属到下级部门',value:'moveDown'},{text:'修改人员备注',value:'update'},{text:'从此部门移除',type: 'warn',value:'moveUp'},{text:'解除公司绑定',type: 'warn',value:'remove'}],
    navbarData:{
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '通讯录', //导航栏 中间的标题
      white:true
     },
     // 导航头的高度
     height: app.globalData.height * 2 + 20
  },
  onLoad:function(options) {
    wx.setNavigationBarTitle({title:options.name});
    this.setData({
      parentId:options.parentId,
      companyId:options.companyId,
      level: parseInt(options.level),
      'navbarData.title':options.name
    });
    requestClient = new ZYRequestClient();
  },
  onShow:function(){
    var _this = this;
    requestClient.getDepartmentResource(_this.data.parentId,function(resource){
      _this.setData({
        departmentList:resource.data.data.departmentVoList,
        userList:resource.data.data.userVoList
      });
    });
  },
  // 下拉刷新
  onPullDownRefresh(e){
    this.onShow();
    wx.stopPullDownRefresh();
  },
  // 跳转下级部门
  bindDepartmentClick:function(e){
    var _this = this;
    var department = e.currentTarget.dataset.department;
    wx.navigateTo({
      url: '/pages/tabbar/contacts/userlist/index?parentId=' + department.id + "&name=" + department.name +"&level=" + (_this.data.level++) + "&companyId=" + _this.data.companyId,
    });
  },
  // 显示添加部门
  showAddDepartment:function(){
    var _this = this;
    requestClient.checkFunctionPermission(3004,'您没有权限添加部门，请联系企业创建者！',function(){
      _this.setData({
        departmentName:"",
        showAddDialog:true
      });
    });
},
  // 长按显示部门操作菜单
  bindDepartmentLongPress:function(e){
    var _this = this;
    _this.setData({
      selectedDepartment:e.currentTarget.dataset.department
    });
    _this.setData({showDepartmentAction:true});
  },
  // 部门操作按钮
  bindDepartmentActionTap:function(e){
    var _this = this;
    _this.setData({showDepartmentAction:false});
    if(e.detail.value == "edit"){
      _this.setData({
        departmentName:"",
        showUpdateDialog:true
      });
    } else {
      wx.showModal({
        title:"解散部门",
        content:"您确定要解散此部门吗？",
        success(e){
          if(e.confirm){
            requestClient.checkFunctionPermission(3006,'您没有权限解散部门，请联系企业创建者！',function(){
              // 解散部门
              requestClient.removeDepartment(_this.data.selectedDepartment.id,function(res){
                    // 加载部门资源
                    requestClient.getDepartmentResource(_this.data.parentId,function(resource){
                      _this.setData({
                        departmentList:resource.data.data.departmentVoList,
                        userList:resource.data.data.userVoList
                      });
                    });
              })
            });
          }
        }
      })
    }
  },
  // 跳转用户信息
  bindUserClick:function(e){
    requestClient.checkFunctionPermission(3007,'您没有权限查看人员，请联系企业创建者！',function(){
      var user = e.currentTarget.dataset.user;
      wx.navigateTo({
        url: '../userinfo/index?id=' + user.id
      });
    });
  },
  // 长按显示用户操作菜单
  bindUserLongPress:function(e){
    var _this = this;
    _this.setData({
      selectedUser:e.currentTarget.dataset.user,
      showUserAction:true
    });
  },
  // 用户操作按钮
  bindUserActionTap:function(e){
    var _this = this;
    _this.setData({showUserAction:false});
    var operate = e.detail.value;
    if(operate == "moveUp"){
      wx.showModal({
        title:'移除用户',
        content:"您确定将用户"+_this.data.selectedUser.nickName + "从"+_this.data.navbarData.title + "移除吗？如果要删除用户请选择解除公司绑定！",
        success(r){
          if(r.confirm){
            var moveUser = {
              userId:_this.data.selectedUser.id,
              departmentId:_this.data.parentId,
              companyId:_this.data.companyId
            };
            requestClient.checkFunctionPermission(3002,'您没有权限移动人员到部门，请联系企业创建者！',function(){
              requestClient.moveUpCompanyUser(moveUser,function(){
                _this.onShow();
              });
            });
          }
        }
      })
    } else if(operate == "update"){
      _this.setData({
        showUserAliasDialog:true
      });
    } else if(operate == "moveDown"){
      _this.setData({
        showCheckDialog:true
      });
    }
    else {
      // 判断是否为本人操作
      var userInfo = wx.getStorageSync('userInfo');
      if(userInfo.id == _this.data.selectedUser.id){
        wx.showModal({
          title:'解绑人员',
          content:'如果您想退出当前企业，可以在我的企业选择退出！',
          showCancel:false,
          success(r){

          }
        })
        return;
      }
      wx.showModal({
        title:"解除绑定",
        content:"您确定要解除用户"+_this.data.selectedUser.nickName + "的绑定吗？",
        success(r){
          if(r.confirm){
            requestClient.checkFunctionPermission(3003,'您没有权限解除人员绑定，请联系企业创建者！',function(){
                // 只有超级管理员才可以删除管理员
                if(_this.checkAdmin(_this.data.selectedUser.id)){
                  if(_this.checkSuperAdmin()){
                    requestClient.removeUser(_this.data.selectedUser.id,_this.data.companyId,function(res){
                      // 加载部门资源
                      requestClient.getDepartmentResource(_this.data.parentId,function(resource){
                        _this.setData({
                          departmentList:resource.data.data.departmentVoList,
                          userList:resource.data.data.userVoList
                        });
                      });
                    });
                  } else {
                    wx.showModal({
                      title:'没有权限',
                      content:'当前用户为管理员，只有企业的创建者才能解除绑定！',
                      showCancel:false,
                      success(r){

                      }
                    })
                  }
                }  else {
                  requestClient.removeUser(_this.data.selectedUser.id,_this.data.companyId,function(res){
                    // 加载部门资源
                    requestClient.getDepartmentResource(_this.data.parentId,function(resource){
                      _this.setData({
                        departmentList:resource.data.data.departmentVoList,
                        userList:resource.data.data.userVoList
                      });
                    });
                  });
                }
            });
          }
        }
      })
    }
  },
  checkAdmin(userId){
    var defaultCompany = wx.getStorageSync('defaultCompany');
    if(userId == defaultCompany.belongUser){
      return true;
    }
    var adminList = defaultCompany.adminList;
    for(var i = 0; i < adminList.length; i++){
      if(userId == adminList[i].id){
        return true;
      }
    }

    return false;
},
  checkSuperAdmin(){
  var userInfo = wx.getStorageSync('userInfo');
  var defaultCompany = wx.getStorageSync('defaultCompany');
  if(userInfo.id == defaultCompany.belongUser){
    return true;
  }

  return false;
},
  // 添加输入框
  formInputChange:function(e){
    this.setData({
      departmentName:e.detail.value
    });
  },
  // 更新输入框
  formUpdateInputChange:function(e){
    this.setData({
      departmentName:e.detail.value
    });
  },
  // 添加部门
  bindAddDepartment:function(e){
    var _this = this;
    _this.setData({
      showAddDialog:false
    });
    if(e.detail.index == 0){
      return ;
    }
    var name = _this.data.departmentName;
    if(name == "" || name.trim() == ""){
        wx.showToast({
          title:"名称不能为空!",
          icon:"error"
        });
        return;
    }
    var userInfo = wx.getStorageSync('userInfo');
    // 构建部门数据
    var departmentData = {
      parentId:_this.data.parentId,
      name:name,
      level:_this.data.level,
      companyId:_this.data.companyId,
      createUser:userInfo.id};
      requestClient.checkFunctionPermission(3004,'您没有权限添加部门，请联系企业创建者！',function(){
        requestClient.addCompanyDepartment(departmentData,function(res){
          // 加载部门资源
          requestClient.getDepartmentResource(_this.data.parentId,function(resource){
                _this.setData({
                  departmentList:resource.data.data.departmentVoList,
                  userList:resource.data.data.userVoList
                });
              });
          });
      });
  },
  // 更新部门名称
  bindUpdateDepartment:function(e){
    var _this = this;
    _this.setData({
      showUpdateDialog:false
    });
    if(e.detail.index == 0){
      return ;
    }
    var name = _this.data.departmentName;
    if(name == "" || name.trim() == ""){
        wx.showToast({
          title:"名称不能为空!",
          icon:"error"
        });
        return;
    }
    requestClient.checkFunctionPermission(3005,'您没有权限编辑部门，请联系企业创建者！',function(){
      requestClient.updateDepartmentName(name,_this.data.selectedDepartment.id,function(res){
        // 加载部门资源
        requestClient.getDepartmentResource(_this.data.parentId,function(resource){
          _this.setData({
            departmentList:resource.data.data.departmentVoList,
            userList:resource.data.data.userVoList
              });
            });
        });
    });
  },
  // 修改人员备注
  bindUpdateUserAlias(e){
    var _this = this;
    _this.setData({
      showUserAliasDialog:false
    });
    if(e.detail.index == 0){
      return ;
    }
    var userAlias = _this.data.userAlias;
    if(userAlias == "" || userAlias.trim() == ""){
        wx.showToast({
          title:"备注不能为空!",
          icon:"error"
        });
        return;
    }
    requestClient.checkFunctionPermission(3009,'您没有权限修改人员备注，请联系企业创建者！',function(){
      requestClient.updateUserAlias(_this.data.selectedUser.id,_this.data.companyId,userAlias,function(res){
        // 加载部门资源
        requestClient.getDepartmentResource(_this.data.parentId,function(resource){
          _this.setData({
            departmentList:resource.data.data.departmentVoList,
            userList:resource.data.data.userVoList
              });
            });
        });
    });
  },
  formUpdateUserAliasChange(e){
    this.setData({
      userAlias:e.detail.value
    });
  },
  // 确认勾选移动的部门
  bindSelectedDepartmentClick(e){
    var _this = this;
    _this.setData({
      showCheckDialog:false
    });
    if(_this.data.checkDepartmentId == 0){
      wx.showToast({
        title: '请选择部门!',
        icon:'error',
        mask:true
      })
      return;
    }
    var moveUser = {
      userId:_this.data.selectedUser.id,
      departmentId:_this.data.checkDepartmentId,
      companyId:_this.data.companyId
    };
    requestClient.checkFunctionPermission(3002,'您没有权限移动人员到部门，请联系企业创建者！',function(){
      requestClient.moveDownCompanyUser(moveUser,function(){
        _this.onShow();
      });
    });
  },
  // 部门勾选变化
  checkboxChange(e){
    this.setData({
      checkDepartmentId:e.detail.value
    });
  }
})
